import {
  defineStore
} from 'pinia'
import {
  clone,
  cloneDeep,
  isEmpty
} from 'lodash-es'
import $router from '@/sheep/router'
import sheep from '@/sheep'
import app from './app'
import {
  showAuthModal,
  closeAuthModal
} from '@/sheep/hooks/useModal'
// 默认用户信息
const defaultUserInfo = {
  menus: [],
  permissions: [],
  roles: [],
  user: {}
}

const user = defineStore({
  id: 'user',
  state: () => ({
    userInfo: clone(defaultUserInfo), // 用户信息
    isLogin: !!uni.getStorageSync('token'), // 登录状态
    lastUpdateTime: 0 // 上次更新时间
  }),

  actions: {
    // 获取个人信息
    async getInfo() {
      // const {
      //   code,
      //   data
      // } = await sheep.$api.system_auth.getPermissionInfo()
      // if (code === 0) {
      //   console.log('data', data)
      //   this.userInfo = data
      //   uni.setStorageSync('userInfo', this.userInfo)
      // }
      // return Promise.resolve(data)
    },

    // 设置token
    setToken(data = null) {
      if (data) {
        uni.setStorageSync('token', data.token)
        uni.setStorageSync('expires_time', data.expires_time)
        uni.setStorageSync('exp', data.exp)
        this.isLogin = true
        this.loginAfter()
      } else {
        this.isLogin = false
        uni.removeStorageSync('token')
        uni.removeStorageSync('expires_time')
        uni.removeStorageSync('exp')
      }
      return this.isLogin
    },

    // 登录后
    async loginAfter() {
      await this.updateUserData()
    },

    // 更新用户相关信息 (手动限流 5秒之内不刷新)
    async updateUserData() {
      // if (!this.isLogin) {
      //   this.resetUserData()
      //   return
      // }
      // const nowTime = new Date().getTime()
      // if (this.lastUpdateTime + 5000 > nowTime) return
      // await this.getInfo()
      // this.lastUpdateTime = nowTime
      // return this.userInfo
      // return this.userInfo
    },

    // 重置用户默认数据
    async resetUserData() {
      this.setToken()
      this.userInfo = clone(defaultUserInfo)
      uni.removeStorageSync('userInfo')
    },
    // 刷新token
    async refreshToken() {

    },
    // 登出
    async loginOut(force = false) {
      // const token = uni.getStorageSync('token')
      // if (!force) {
      //   const {
      //     code
      //   } = await sheep.$api.system_auth.loginOut()
      //   if (code === 0) {
      //     this.resetUserData()
      //   }
      // }
      // if (force || !token) {
      //   this.resetUserData()
      // }
			this.resetUserData()
      $router.go('/pages/index/login')
      return !this.isLogin
    }
  },
  persist: {
    enabled: true,
    strategies: [{
      key: 'user-store'
    }]
  }
})

export default user
